# CONFIGURE THE SERVER
# --------------------------------------------------------------------------
# Define the basic configuration options for the node server, depending on
# the current environment.

module.exports = (app, express) ->

    # Load settings.
    database = require "./database.coffee"
    logger = require "./logger.coffee"
    mail = require "./mail.coffee"
    settings = require "./settings.coffee"
    twitter = require "./twitter.coffee"

    # Check if there are misconfigured settings on the app. Wrong settings will be logged to the console.
    checkSettings = ->
        # Database.maxRetries must greater than 0. Will default to 1.
        if settings.Database.maxRetries < 1
            console.warn "Configure.checkSettings", "Database.maxRetries: #{settings.Database.maxRetries}, must be a positive value.", "Setting to 1."
            settings.Database.maxRetries = 1
        # Email SMTP port must be a number greater than 0. Will default to 25.
        if settings.Email.smtpPort? and settings.Email.smtpPort < 0
            console.warn "Configure.checkSettings", "Database.maxRetries: #{settings.Database.maxRetries}, must be a positive value.", "Setting to 1."
            settings.Email.smtpPort = 25
        # Make sure Twitter checking intervals is not less than 20 seconds.
        if settings.Twitter.inboxCheckInterval? and settings.Twitter.inboxCheckInterval > 0 and settings.Twitter.inboxCheckInterval < 20
            console.warn "Configure.checkSettings", "Twitter.inboxCheckInterval: #{settings.Twitter.inboxCheckInterval}, must be at least 20.", "Setting to 20."
            settings.Twitter.inboxCheckInterval = 20
        if settings.Twitter.scheduledCheckInterval? and settings.Twitter.scheduledCheckInterval > 0 and settings.Twitter.scheduledCheckInterval < 20
            console.warn "Configure.checkSettings", "Twitter.scheduledCheckInterval: #{settings.Twitter.scheduledCheckInterval}, must be at least 20.", "Setting to 20."
            settings.Twitter.scheduledCheckInterval = 20

    # Make it PaaS friendly. Check for environment variables to override specific settings.
    # If no environment variables are found, the app will use whatever is defined on the
    # [settings](settings.html). This is called ONLY if the `paas` web setting is true.
    checkCloudEnvironment = ->
        # Check for web (IP and port) variables.
        ip = process.env.OPENSHIFT_INTERNAL_IP
        port = process.env.OPENSHIFT_INTERNAL_PORT
        port = process.env.VCAP_APP_PORT if not port? or port is ""
        settings.Web.ip = ip if ip? and ip isnt ""
        settings.Web.port = port if port? and port isnt ""

        # Check for MongoDB variables.
        vcap = process.env.VCAP_SERVICES
        vcap = JSON.parse vcap if vcap?
        if vcap? and vcap isnt ""
            mongo = vcap["mongodb-1.8"]
            mongo = mongo[0]["credentials"] if mongo?
            if mongo?
                settings.Database.connString = "mongodb://#{mongo.hostname}:#{mongo.port}/#{mongo.db}"

        # Check for logging variables.
        logentriesToken = process.env.LOGENTRIES_TOKEN
        logglyToken = process.env.LOGGLY_TOKEN
        logglySubdomain = process.env.LOGGLY_SUBDOMAIN
        settings.Log.Logentries.token = logentriesToken if logentriesToken? and logentriesToken isnt ""
        settings.Log.Loggly.token = logglyToken if logglyToken? and logglyToken isnt ""
        settings.Log.Loggly.subdomain = logglySubdomain if logglySubdomain? and logglySubdomain isnt ""

    # General configuration of the app (for all environments).
    app.configure ->
        checkSettings()
        checkCloudEnvironment() if settings.Web.paas

        # Init the logger.
        logger.init()

        # Init modules.
        database.init()
        mail.init()
        twitter.init()

        # Set view options, use Jade for HTML templates.
        app.set "views", settings.Path.viewsDir
        app.set "view engine", "jade"
        app.set "view options", { layout: false }

        # Express settings.
        app.use express.bodyParser()
        app.use express.cookieParser settings.Web.cookieSecret
        app.use express.compress()
        app.use express.methodOverride()
        app.use express["static"] settings.Path.publicDir
        app.use express.favicon __dirname + "/../favicon.ico"
        app.use app.router

        # Connect assets and dynamic compiling.
        ConnectAssets = (require "connect-assets") settings.ConnectAssets
        app.use ConnectAssets

    # Configure development environment.
    app.configure "development", ->
        app.use express.errorHandler settings.ErrorHandling

    # Configure production environment.
    app.configure "production", ->
        app.use express.errorHandler()